import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm, Controller } from 'react-hook-form';
import { z } from 'zod';
import {
  Box,
  Typography,
  Paper,
  TextField,
  Button,
  Stack,
  FormControlLabel,
  Switch,
  Alert,
  CircularProgress,
  Divider,
  Chip,
  Autocomplete,
  IconButton,
  Tooltip,
} from '@mui/material';
import {
  ArrowBack as ArrowBackIcon,
  Save as SaveIcon,
  HelpOutline as HelpIcon,
  Computer as ComputerIcon,
  Link as LinkIcon,
} from '@mui/icons-material';
import { useConnectionStore } from '../../stores/connectionStore';

// 表单验证schema
const connectionSchema = z.object({
  name: z.string().min(1, '连接名称不能为空').max(50, '连接名称不能超过50个字符'),
  uri: z.string().min(1, 'URI不能为空').url('请输入有效的URI'),
  set_as_default: z.boolean().optional(),
});

type ConnectionFormData = z.infer<typeof connectionSchema>;

// 预设的URI模板
const uriTemplates = [
  { label: '本地 QEMU/KVM', value: 'qemu:///system' },
  { label: '本地 QEMU 用户会话', value: 'qemu:///session' },
  { label: '本地 LXC', value: 'lxc:///' },
  { label: '本地 Xen', value: 'xen:///' },
  { label: '远程 QEMU+SSH', value: 'qemu+ssh://user@host/system' },
  { label: '远程 QEMU+TCP', value: 'qemu+tcp://host:16509/system' },
  { label: '远程 QEMU+TLS', value: 'qemu+tls://host:16514/system' },
  { label: 'ESXi/vSphere', value: 'esx://host/?no_verify=1' },
  { label: 'VMware Workstation', value: 'vmwarews:///var/run/vmware' },
  { label: 'VirtualBox', value: 'vbox:///session' },
  { label: 'Hyper-V', value: 'hyperv:///' },
];

const ConnectionCreate: React.FC = () => {
  const navigate = useNavigate();
  const { createConnection, loading, error, clearError } = useConnectionStore();
  const [submitError, setSubmitError] = useState<string | null>(null);

  const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
  } = useForm<ConnectionFormData>({
    // resolver: zodResolver(connectionSchema),
    defaultValues: {
      name: '',
      uri: '',
      set_as_default: true,
    },
  });

  const watchUri = watch('uri');

  const onSubmit = async (data: ConnectionFormData) => {
    try {
      // 手动验证
      const result = connectionSchema.safeParse(data);
      if (!result.success) {
        const firstError = result.error.issues[0];
        setSubmitError(firstError.message);
        return;
      }

      setSubmitError(null);
      await createConnection(data);
      navigate('/connections');
    } catch (error: any) {
      setSubmitError(error.message || '创建连接失败');
    }
  };

  const handleBack = () => {
    navigate('/connections');
  };

  const handleUriTemplateSelect = (template: string) => {
    setValue('uri', template);
  };

  const handleTestConnection = async () => {
    // TODO: 实现连接测试功能
    console.log('测试连接功能待实现');
  };

  return (
    <Box>
      {/* 页面标题和操作栏 */}
      <Box sx={{ mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <IconButton onClick={handleBack} sx={{ color: 'text.secondary' }}>
              <ArrowBackIcon />
            </IconButton>
            <Typography variant="h4" component="h1" fontWeight="bold">
              创建连接
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button
              variant="outlined"
              onClick={handleTestConnection}
              disabled={!watchUri || loading}
            >
              测试连接
            </Button>
            <Button
              variant="contained"
              startIcon={loading ? <CircularProgress size={20} /> : <SaveIcon />}
              onClick={handleSubmit(onSubmit)}
              disabled={loading}
            >
              创建连接
            </Button>
          </Box>
        </Box>
      </Box>

      {/* 错误提示 */}
      {(error || submitError) && (
        <Alert 
          severity="error" 
          sx={{ mb: 2 }} 
          onClose={() => {
            clearError();
            setSubmitError(null);
          }}
        >
          {error || submitError}
        </Alert>
      )}

      <Stack spacing={3}>
        {/* 连接信息表单 */}
        <Paper variant="outlined" sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            连接配置
          </Typography>
          
          <Stack spacing={3}>
            <Controller
              name="name"
              control={control}
              render={({ field }) => (
                <TextField
                  {...field}
                  label="连接名称"
                  placeholder="例如: 本地KVM"
                  fullWidth
                  error={!!errors.name}
                  helperText={errors.name?.message}
                  InputProps={{
                    startAdornment: (
                      <ComputerIcon sx={{ color: 'text.secondary', mr: 1 }} />
                    ),
                  }}
                />
              )}
            />

            <Controller
              name="uri"
              control={control}
              render={({ field }) => (
                <Autocomplete
                  {...field}
                  freeSolo
                  options={uriTemplates}
                  getOptionLabel={(option) => typeof option === 'string' ? option : option.label}
                  renderOption={(props, option) => (
                    <li {...props}>
                      <Box sx={{ display: 'flex', flexDirection: 'column', py: 1 }}>
                        <Typography variant="body2" fontWeight="medium">
                          {typeof option === 'string' ? option : option.label}
                        </Typography>
                        {typeof option !== 'string' && (
                          <Typography variant="caption" color="text.secondary">
                            {option.value}
                          </Typography>
                        )}
                      </Box>
                    </li>
                  )}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="连接URI"
                      placeholder="例如: qemu:///system"
                      fullWidth
                      error={!!errors.uri}
                      helperText={errors.uri?.message || 'URI格式: driver[+transport]://[user@][host][:port]/[path][?extraparams]'}
                      InputProps={{
                        ...params.InputProps,
                        startAdornment: (
                          <LinkIcon sx={{ color: 'text.secondary', mr: 1 }} />
                        ),
                        endAdornment: (
                          <>
                            <Tooltip title="URI格式帮助">
                              <IconButton size="small" sx={{ mr: 1 }}>
                                <HelpIcon fontSize="small" />
                              </IconButton>
                            </Tooltip>
                            {params.InputProps.endAdornment}
                          </>
                        ),
                      }}
                    />
                  )}
                  onChange={(_, value) => {
                    if (typeof value === 'string') {
                      field.onChange(value);
                    } else if (value) {
                      field.onChange(value.value);
                    }
                  }}
                />
              )}
            />

            <Controller
              name="set_as_default"
              control={control}
              render={({ field }) => (
                <FormControlLabel
                  control={
                    <Switch
                      {...field}
                      checked={field.value}
                      onChange={(e) => field.onChange(e.target.checked)}
                    />
                  }
                  label="设为默认连接"
                />
              )}
            />
          </Stack>
        </Paper>

        {/* URI模板快速选择 */}
        <Paper variant="outlined" sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            快速选择URI模板
          </Typography>
          <Typography variant="body2" color="text.secondary" gutterBottom>
            选择预设的URI模板快速配置连接
          </Typography>
          <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
            {uriTemplates.map((template) => (
              <Chip
                key={template.value}
                label={template.label}
                onClick={() => handleUriTemplateSelect(template.value)}
                variant={watchUri === template.value ? 'filled' : 'outlined'}
                color={watchUri === template.value ? 'primary' : 'default'}
              />
            ))}
          </Stack>
        </Paper>

        {/* 连接信息提示 */}
        <Paper variant="outlined" sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            连接信息
          </Typography>
          <Stack spacing={2}>
            <Box>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                支持的虚拟化驱动:
              </Typography>
              <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
                <Chip label="QEMU/KVM" size="small" />
                <Chip label="Xen" size="small" />
                <Chip label="LXC" size="small" />
                <Chip label="VirtualBox" size="small" />
                <Chip label="VMware" size="small" />
                <Chip label="Hyper-V" size="small" />
              </Stack>
            </Box>
            
            <Divider />
            
            <Box>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                常用URI示例:
              </Typography>
              <Stack spacing={1}>
                <Box>
                  <Typography variant="caption" component="code" sx={{ fontFamily: 'monospace' }}>
                    qemu:///system
                  </Typography>
                  <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
                    - 本地系统级QEMU/KVM
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" component="code" sx={{ fontFamily: 'monospace' }}>
                    qemu+ssh://user@host/system
                  </Typography>
                  <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
                    - 远程SSH连接
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" component="code" sx={{ fontFamily: 'monospace' }}>
                    qemu+tcp://host:16509/system
                  </Typography>
                  <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
                    - TCP连接（不安全）
                  </Typography>
                </Box>
              </Stack>
            </Box>
          </Stack>
        </Paper>
      </Stack>
    </Box>
  );
};

export default ConnectionCreate;